import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入Login组件
import Login from "@/components/Login.vue"
// 引入Home组件
import Home from "@/components/Home.vue"
// 引入Welcome组件
import Welcome from "@/components/Welcome.vue"
// 引入UserList
import UserList from "@/components/admin/UserList.vue"
import Food from "@/components/user/Food.vue"
import Calories from "@/components/user/Calories.vue"
import Introduction from "@/components/admin/Introduction.vue"
import Goods from "@/components/admin/Goods.vue"
import Sport from "@/components/user/Sport.vue"
import Rights from "@/components/admin/Rights.vue"

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect:"/login",
  },
  {
    path: "/login",
    component: Login
  },
  {
    path:"/home",
    component: Home,
    // Main主体重定向
    redirect:"/welcome",
    children:[
        {path:"/welcome" ,component: Welcome},
        {path:"/user" ,component: UserList},
        {path:"/rights" ,component: Rights},
        {path:"/sport" ,component: Sport},
        {path:"/goods" ,component: Goods},
        {path:"/Introduction" ,component: Introduction},
        {path:"/calories" ,component: Calories},
        {path:"/food" ,component: Food},
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫 防止根据url地址跳过登陆页直接进入其它页面
router.beforeEach((to,from,next) =>{
  // to 将要访问
  // from 从访问
  // next 接着做什么 next(url) 重定向到url上 next() 继续访问 to路径
  if(to.path == '/login') return next();
  // 获取user
  const userFlag = window.sessionStorage.getItem("user");// 取出当前用户
  if (!userFlag) return next('/login'); //无值则返回登陆页
  next();//符合要求
})

export default router
